/* eslint-disable react/jsx-indent */
import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Table,
  Button,
  Select,
  Pagination,
  Modal,
  Tooltip,
  message,
} from 'antd';

import { TableListData } from './data';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { pathname } = window.location;

const pagination: any = {
  display: 'flex',
  justifyContent: 'flex-end',
};

interface ElectronicSurfaceSingleListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  location: { query: any };
  dataInfo: TableListData;
  INITINFO: any;
  screen: string;
}

interface ElectronicSurfaceSingleListState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  JurisdictionModal: boolean;
}

@connect(
  ({
    electronicSurfaceSingleList: { dataInfo },
    common: { INITINFO },
    global: { screen },
    loading,
  }: any) => ({
    dataInfo,
    INITINFO,
    screen,
    loading: loading.effects['electronicSurfaceSingleList/fetch'],
  }),
)
class ElectronicSurfaceSingleListElem extends Component<ElectronicSurfaceSingleListProps,
ElectronicSurfaceSingleListState> {
  columns = [
    {
      title: '寄件地址',
      width: 150,
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '网点名称',
      dataIndex: 'branchName',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '网点编码',
      dataIndex: 'branchCode',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '余额',
      dataIndex: 'quantity',
      width: 100,
    },
    {
      title: '授权人',
      dataIndex: 'updateUser',
      width: 80,
    },
    {
      title: '授权时间',
      dataIndex: 'createTime',
      width: 180,
    },
    {
      title: '剩余授权时间',
      dataIndex: 'expireTime',
      width: 100,
      render: (val: number) => <div className="wordOmit">{val}天</div>,
    },
  ];

  state: ElectronicSurfaceSingleListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    JurisdictionModal: false,
  };

  static getDerivedStateFromProps(nextProps: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.fetchExpressList();
    this.setFieldsValue();
    this.fetchTableList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchTableList();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues: { expressId } } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ expressId });
  };

  // 获取快递公司列表
  fetchExpressList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchExpressList',
      payload: { name: '' },
    });
  };

  // 获取数据
  fetchTableList = () => {
    const { location: { query: { logisId } } } = this.props;
    if (logisId) {
      const { dispatch } = this.props;
      dispatch({
        type: 'electronicSurfaceSingleList/fetch',
        payload: this.getQueryParams(),
      });
    } else {
      message.warning('请先选择物流中心');
    }
  };

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params: any = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { searchValues } = this.state;
      const params = {
        ...searchValues,
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { location: { query: { logisName } } } = this.props;
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: `查看${logisName}电子面单`,
        url: `${pathname}?${qs.stringify(params)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { location: { query: { logisId, logisName } } } = this.props;
    const params = { logisId, logisName };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${logisName}电子面单`,
      url: `${pathname}?${qs.stringify(params)}`,
      isTopMenu: true,
    });
  };

  handleJurisdictionModal = (JurisdictionModal: boolean) => this.setState({ JurisdictionModal });

  handleSureCancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'electronicSurfaceSingleList/cancel',
      payload: {
        search: this.getQueryParams(),
        logisId: this.getQueryParams().logisId,
      },
    });

    this.handleJurisdictionModal(false);
  };

  onSelectChange = (pageIndex: number, pageSize?: number) => {
    const { searchValues } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };

    const { location: { query: { logisName } } } = this.props;
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${logisName}电子面单`,
      url: `${pathname}?${qs.stringify(params)}`,
      isTopMenu: true,
    });
  };

  renderTableListElem = () => {
    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { expressList },
    } = this.props;

    const { pageIndex, pageSize } = this.state;

    const dataContent: any = dataInfo.list || {};

    const addressItem: any = {
      position: 'absolute',
      fontWeight: '600',
      width: '180px',
      zIndex: '2',
      left: '23px',
      top: '80px',
    };

    return (
      <Fragment>
        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12} justify="space-between">
              <Col md={6} sm={24}>
                <Form.Item label="快递公司">
                  {getFieldDecorator('expressId')(
                    <Select
                      showSearch
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {expressList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24} className="mobileT">
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            {
              dataInfo.code === 10201 && (
                <Button
                  type="primary"
                  size="small"
                  className="smallButton marginR16"
                  onClick={() => window.open(dataInfo.authorizationUrl)}
                >
                  电子面单授权
                </Button>
              )
            }
            {
              dataInfo.code === 0 && (
                <Fragment>
                  <Button
                    type="primary"
                    size="small"
                    className="smallButton marginR16"
                    onClick={() => window.open(dataInfo.reapplyUrl)}
                  >
                    重新授权
                  </Button>
                  <Button
                    type="danger"
                    size="small"
                    className="smallButton marginR16"
                    onClick={() => this.handleJurisdictionModal(true)}
                  >
                    取消授权
                  </Button>
                </Fragment>
              )
            }
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => window.open(dataInfo.applyUrl)}
            >
              申请电子面单
            </Button>
          </div>
          {
            Object.keys(dataContent).map((addr: any) => (
              <div key={addr} style={{ position: 'relative' }}>
                <div style={addressItem}>{addr}</div>
                <Table
                  rowKey={addr}
                  tableLayout="fixed"
                  className="statementTable tableHeight60"
                  columns={this.columns}
                  dataSource={dataContent[addr]}
                  pagination={false}
                  scroll={{ x: 980 }}

                />
              </div>
            ))
          }
          {
            dataInfo.count
              ? (
                <Pagination
                  className="marginTop20"
                  total={Object.keys(dataContent).length}
                  current={pageIndex}
                  pageSize={pageSize}
                  style={pagination}
                  showQuickJumper
                  showSizeChanger
                  pageSizeOptions={['10', '20', '50', '100']}
                  showTotal={total => `共${total || 0}条数据`}
                  onChange={this.onSelectChange}
                  onShowSizeChange={this.onSelectChange}
                />
              )
              : (
                <Card className="marginT12">
                  <div style={{ textAlign: 'center', padding: '30px 0px' }}>暂无数据...</div>
                </Card>
              )
          }
        </Card>
      </Fragment>
    );
  };

  render() {
    const { JurisdictionModal } = this.state;
    return (
      <Fragment>
        <PageHeader />
        {this.renderTableListElem()}
        <Modal
          visible={JurisdictionModal}
          title="确认提示"
          onOk={this.handleSureCancel}
          onCancel={() => this.handleJurisdictionModal(false)}
        >
          <p>取消授权后将不能进行电子面单打印服务，请谨慎操作</p>
        </Modal>
      </Fragment>
    );
  }
}

export default Form.create<ElectronicSurfaceSingleListProps>()(ElectronicSurfaceSingleListElem);
